package Wizard.Android;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Environment;
import android.util.Log;

public class RootSystemManager extends Activity {
	public String packageCodePath;

	public RootSystemManager(String packageCodePath) {
		// TODO Auto-generated constructor stub
		this.packageCodePath = packageCodePath;
	}

	private boolean RootCommand(String apkuri) {
		System.out.println("apkuri=" + packageCodePath);
		Process process = null;
		DataOutputStream os = null;
		String command = "";
		try {
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			command = "chmod 777 " + packageCodePath + "\n";
			os.writeBytes(command);
			os.flush();
			command = "pm install -r " + apkuri + "\n";
			os.writeBytes(command);
			os.flush();
			process.waitFor();
		} catch (Exception e) {
			Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
			return false;
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				process.destroy();
			} catch (Exception e) {
			}
		}
		Log.d("*** DEBUG ***", "Root SUC ");
		return true;
	}

	public void downFile(final String uri) {
		String bufNa[] = uri.replace("/", "-").split("-");
		final String newVerName = bufNa[bufNa.length - 1];
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(uri);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(
								Environment.getExternalStorageDirectory(),
								newVerName);
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;
							if (length > 0) {
							}
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					if (RootCommand(Environment.getExternalStorageDirectory()
							+ "/" + newVerName)) {
						System.out.println("inssal_OK");
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
}
